<template>
  <el-form ref="formRef" v-loading="loading" :model="formData" :rules="rules" label-width="120" size=""
    style="padding-right: 10px; overflow: auto">
    <el-row justify="start" style="margin-top: 10px">
      <el-col :span="5" :offset="0" align="center">
        <el-row :gutter="20">
          <el-col style="padding-top: 15px">
            <div style="width: 150px; height: 150px; background-color: rgb(231, 231, 233)">
              <svg-icon v-if="formData.token == undefined" icon-class="peopleheader" size="95%" />
              <el-image v-else style="width: 100%; height: 100%" :src="cardInfo.headPic" fit="fill" />
            </div>
          </el-col>
          <el-col v-if="optionType == 1" style="padding-top: 15px">
            <el-button type="primary" :loading="resolveLoading" @click="resolveCard">读身份证</el-button>
          </el-col>
          <el-col v-if="optionType == 1" style="padding-top: 15px">
            <el-text class="mx-1" type="warning">请使用身份证识别器读取数据</el-text>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="19" :offset="0">
        <el-row justify="start" :gutter="20">
          <el-col :span="8">
            <el-form-item label="身份证号" prop="token">
              <el-input v-model="cardInfo.id" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="token">
              <el-input v-model="cardInfo.name" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="token">
              <el-input v-model="cardInfo.sex" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="出生日期" prop="token">
              <el-input v-model="cardInfo.birth" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发证机关" prop="token">
              <el-input v-model="cardInfo.company" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族" prop="token ">
              <el-input v-model="cardInfo.nationality" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="证件有效期" prop="token">
              <el-input v-model="cardInfo.beginDate" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="至" prop="token">
              <el-input v-model="cardInfo.endDate" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="cardInfo.address" placeholder="自动识别" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码" prop="mobile">
              <el-input ref="mobileRef" v-model="formData.mobile" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况" prop="maritalStatus">
              <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状况" clearable>
                <el-option v-for="item in maritalStatus" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌" prop="politicsType">
              <el-select v-model="formData.politicsType" placeholder="请选择政治面貌" clearable>
                <el-option v-for="item in politicsType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急联系人" prop="urgentLinkman">
              <el-input v-model="formData.urgentLinkman" placeholder="请输入紧急联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急联系电话" prop="urgentLinkmanHone">
              <el-input v-model="formData.urgentLinkmanHone" placeholder="请输入紧急联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="加入公会日期" prop="joinedTime">
              <el-date-picker v-model="formData.joinedTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="特长" prop="specialty">
              <el-input v-model="formData.specialty" placeholder="请输入特长" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文化程度" prop="cultureLevel">
              <el-select v-model="formData.cultureLevel" placeholder="请选择文化程度" clearable>
                <el-option v-for="item in cultureLevel" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否有重大病史" prop="hasBadMedicalHistory">
              <el-select v-model="formData.hasBadMedicalHistory" placeholder="请选择是否有重大病史" clearable>
                <el-option :key="true" label="是" :value="true" />
                <el-option :key="false" label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item class="last-item" label="是否购买工伤或意外伤害保险" prop="hasBuyInsurance">
              <el-select v-model="formData.hasBuyInsurance" class="last-select" placeholder="请选择否购买保险" clearable>
                <el-option :key="true" label="是" :value="true" />
                <el-option :key="false" label="否" :value="false" />
              </el-select>
              <!-- <div>是否购买工伤或意外伤害保险</div> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <modelPromise v-if="dialogModel.visible" :dialog-model="dialogModel" @send-model-close="sendModelClose">
    </modelPromise>
  </el-form>
</template>
<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { getDicts } from "@/store/modules/dict";
import { PersonCreateForm } from "@/api/worker/types";
import { CardDeviceSocketPromise } from "@/utils/cardDevice";
import { FormRules } from "element-plus/es/components/form/src/types";
import moment from "moment";
const loading = ref(false);
const resolveLoading = ref(false);
const formData = reactive<PersonCreateForm>({});
const maritalStatus = getDicts("maritalStatus");
const politicsType = getDicts("politicsType");
const cultureLevel = getDicts("cultureLevel");
const chineseEthnicity = getDicts("chineseEthnicity");
const gender = getDicts("gender");
const formRef = ref(ElForm);
const rules = reactive<FormRules<PersonCreateForm>>({
  mobile: [
    {
      required: true,
      message: "请输入手机号码",
      trigger: "blur",
    },
    {
      pattern: /^1[34578]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  token: [
    {
      required: true,
      message: "请先读取身份证信息",
      trigger: "blur",
    },
  ],
});
const cardInfo = ref<any>({});
const cacheForm = ref<any>({});
//默认缓存表单的的key
const cacheKey = ref("addWorkerBasicInfo");

//1：新增 2 修改 3 详情(详情不再使用当前页面)
const optionType = ref(1);
const mobileRef = ref();
const dialogModel = reactive({
  visible: false,
  detail: "corp",
  code: "",
});
function sendModelClose() {
  dialogModel.visible = false;
}

/* 读取身份证 */
const resolveCard = () => {
  resolveLoading.value = true;
  CardDeviceSocketPromise()
    .then((data: any) => {
      console.log(data);
      cardInfo.value = data;
      cardInfo.value.sex = gender.find((item: any) => item.value == data.sex)?.label;
      cardInfo.value.nationality = chineseEthnicity.find((item: any) => item.value == data.race)?.label;
      cardInfo.value.birth = moment(data.birth).format("YYYY-MM-DD");
      cardInfo.value.beginDate = moment(data.beginDate).format("YYYY-MM-DD");
      cardInfo.value.endDate = moment(data.endDate).format("YYYY-MM-DD");
      cardInfo.value.headPic = "data:image/png;base64," + data.headPic;
      console.log(data);
      formData.token = data.token;
      resolveLoading.value = false;
      mobileRef.value.focus();
    })
    .finally(() => {
      resolveLoading.value = false;
    });
};

const getCardInfo = async (e: any) => {
  let result = JSON.parse(e.data);
  let { success, msg, data } = result;
  if (!success) {
    if (msg == "版本不一致") {
      // if (msg) {
      let box = await ElMessageBox({
        title: "程序下载",
        showCancelButton: true,
        showConfirmButton: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        message: () =>
          h(
            "div",
            {
              style: {},
            },
            [
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                `当前身份证阅读器守护程序版本已过期，请关闭现有程序并点击下面链接重新下载。`
              ),
              h("br", null, null),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "程序下载地址"
              ),
              h(
                "a",
                {
                  href: "/app/cardreader-setup-20230907.exe",
                  target: "_blank",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击下载"
              ),
              h("br", null, null),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "有关读卡器守护程序使用教程请"
              ),
              h(
                "a",
                {
                  href: "/app/tutorial.html",
                  target: "_blank",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击查看"
              ),
            ]
          ),
      })
        .then((val) => true)
        .catch((val) => false);
    } else if (msg == "身份证读卡器信息未登记") {
      dialogModel.visible = true;
    } else {
      ElMessage.error(msg);
    }
    return;
  }
  cardInfo.value = data;
  cardInfo.value.sex = gender.find((item: any) => item.value == data.sex)?.label;
  cardInfo.value.nationality = chineseEthnicity.find((item: any) => item.value == data.race)?.label;
  cardInfo.value.birth = moment(data.birth).format("YYYY-MM-DD");
  cardInfo.value.beginDate = moment(data.beginDate).format("YYYY-MM-DD");
  cardInfo.value.endDate = moment(data.endDate).format("YYYY-MM-DD");
  cardInfo.value.headPic = "data:image/png;base64," + data.headPic;
  console.log(data);
  formData.token = data.token;
  resolveLoading.value = false;
};
const initForm = (data?: any, type?: number) => {
  if (data) {
    optionType.value = type ?? 2;
    cardInfo.value.headPic = data.base64PhotoStr;
    cardInfo.value.nationality = data.nation;
    cardInfo.value.sex = gender.find((item: any) => item.value == data.gender)?.label;
    cardInfo.value.birth = data.birthday;
    cardInfo.value.beginDate = data.cardStartdate;
    cardInfo.value.endDate = data.cardEnddate;
    cardInfo.value.id = data.cardNumber;
    cardInfo.value.name = data.name;
    cardInfo.value.company = data.cardOrg;
    cardInfo.value.address = data.address;
    formData.token = "update";
    Object.assign(formData, data);
  }
  initCacheForm();
};

//重置缓存表单
const initCacheForm = () => {
  if (optionType.value == 2) return;
  var cacheJson = localStorage.getItem(cacheKey.value);
  if (cacheJson) {
    cacheForm.value = JSON.parse(cacheJson);
  } else {
    cacheForm.value = {
      maritalStatus: undefined,
      politicsType: undefined,
      urgentLinkman: undefined,
      urgentLinkmanHone: undefined,
      joinedTime: undefined,
      specialty: undefined,
      cultureLevel: undefined,
      hasBadMedicalHistory: undefined,
      hasBuyInsurance: undefined,
    };
  }
  Object.assign(formData, cacheForm.value);
};
//更新缓存表单
watchEffect(() => {
  cacheForm.value.maritalStatus = formData.maritalStatus;
  cacheForm.value.politicsType = formData.politicsType;
  cacheForm.value.urgentLinkman = formData.urgentLinkman;
  cacheForm.value.urgentLinkmanHone = formData.urgentLinkmanHone;
  cacheForm.value.joinedTime = formData.joinedTime;
  cacheForm.value.specialty = formData.specialty;
  cacheForm.value.cultureLevel = formData.cultureLevel;
  cacheForm.value.hasBadMedicalHistory = formData.hasBadMedicalHistory;
  cacheForm.value.hasBuyInsurance = formData.hasBuyInsurance;
});
//保存需要保存的表单
const saveCacheForm = () => {
  if (optionType.value == 2) return;
  console.log("保存缓存表单");
  localStorage.setItem(cacheKey.value, JSON.stringify(cacheForm.value));
};

onMounted(() => {
  //初始化表单
  initForm();
});

/**
 * 重置表单
 */
const resetForm = () => {
  formData.token = undefined;
  cardInfo.value = {};
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  formData.maritalStatus = cacheForm.value.maritalStatus;
  formData.politicsType = cacheForm.value.politicsType;
  formData.urgentLinkman = cacheForm.value.urgentLinkman;
  formData.urgentLinkmanHone = cacheForm.value.urgentLinkmanHone;
  formData.joinedTime = cacheForm.value.joinedTime;
  formData.specialty = cacheForm.value.specialty;
  formData.cultureLevel = cacheForm.value.cultureLevel;
  formData.hasBadMedicalHistory = cacheForm.value.hasBadMedicalHistory;
  formData.hasBuyInsurance = cacheForm.value.hasBuyInsurance;
};
/*表单校验*/
const validation = async () => {
  if (formData.token == undefined || formData.token == null || formData.token == "") {
    ElMessage.error("请先读取身份证信息!");
    return;
  }
  return await formRef.value.validate();
};

defineExpose({
  resetForm,
  validation,
  formData,
  initForm,
  saveCacheForm,
});
</script>

<style scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}

.last-select {
  left: 120px;
  width: 170px;
}

:deep(.last-item label) {
  position: absolute;
  width: 200px !important;
  left: -70px;
}
</style>
